package com.wecommodule.bpm.ext.biz.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSONObject;
import com.wecommodule.bpm.ext.biz.config.WxConfig;
import com.wecommodule.bpm.ext.biz.entity.EnterpriseVo;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.api.impl.WxCpMessageServiceImpl;
import me.chanjar.weixin.cp.bean.message.WxCpMessage;
import me.chanjar.weixin.cp.bean.message.WxCpMessageSendResult;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.net.URLEncoder;
import java.util.HashMap;

@RestController
@Slf4j
public class WxConstructOauthController {
    @Resource
    RedisTemplate<String, String> redisTemplateString;

    /**
     * 构建oauth链接
     *
     * @return {@link String}
     */
    @GetMapping("/constructOauthLink")
    public String constructOauthLink(String userId, String serviceName) {
        //TODO 这里需要改造成根据接口传入的成员姓名或者userID ，然后去构造成员所属的企业微信应用去推送授权链接
        //可信域名的接口地址用来接收企业微信回传的code，用户点击构造
//        String redirectUri = "https://8164c0cc874549a6aa31385aebfea4a8.apig.cn-east-3.huaweicloudapis.com";
        String redirectUri = "https://mobiletest.chinacdc.com:18888/wecommodule/";
        //微信固定API地址
        String wysqlj = "https://open.weixin.qq.com/connect/oauth2/authorize";
        //构造授权链接参数 appid：企业的CorpID   state ：服务内容   agentid：应用唯一id
        String appid = "wwe24d68910965e032";
        String status = "serviceName";
        String agentid = "1000002";
        //对科接口回调地址进行url编码
        String redirectUriEncoder = URLEncoder.encode(redirectUri);
        //构造授权连接  snsapi_base：静默授权，可获取成员的基础信息（UserId与DeviceId）,snsapi_privateinfo：手动授权，可获取成员的详细信息，包含头像、二维码等敏感信息。
        String url = wysqlj + "?appid=" + appid + "&redirect_uri=" + redirectUriEncoder + "&response_type=code&scope=snsapi_privateinfo&state=" + status + "&agentid=" + agentid + "#wechat_redirect";
        //生成二维码，识别二维码授权企业微信，但企业微信不支持
    /*    String basePath = "D:\\commonTest\\";
        String bgtuPath = "D:\\commonTest\\tex\\";
        String url1 = "http://www.xiqianyangyi.com/leaveMessage";
        String path = basePath + System.currentTimeMillis() + ".png";
        File filea = QrCodeUtil.generate(url,
                QrConfig.create(), //附带logo
                FileUtil.file(path)//写出到的文件
        );*/
        return sendTextCardMsg(userId, serviceName, url);

    }

    /**
     * 获取成员票据
     *
     * @param code 代码
     * @return {@link HashMap}<{@link String},{@link Object}>
     * @throws WxErrorException wx错误异常
     */
    @GetMapping("/getUserTicket")
    public String getUserTicket(String code) throws WxErrorException {
        WxCpService wxCpService = WxConfig.getWxCpService(redisTemplateString);
        String accessToken = wxCpService.getAccessToken();
        log.info("通过微信的服务类获取的token： {}",accessToken);
        String wxAccessToken = "wx"+EnterpriseVo.getCorpId();
        String accessToken1 = redisTemplateString.opsForValue().get(wxAccessToken);
        JSONObject jsonObject = JSONObject.parseObject(accessToken1);
        Object accessToken2 = jsonObject.get("accessToken");
        System.out.println("两个token是否相等===="+accessToken.equals(accessToken2));
        log.info("通过Redis获取的token： {}",accessToken2);
        String url = "https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo?access_token=ACCESS_TOKEN&code=CODE";
        url = url.replace("ACCESS_TOKEN",accessToken).replace("CODE",code);
        String res = HttpRequest.get(url).execute().body();
        log.info("从企微接口:{}\n获取访问用户成员票据结果:{}",url,res);
        JSONObject result = JSONObject.parseObject(res);
        HashMap<String, Object> map = new HashMap<>();
        if (!"0".equals(String.valueOf(result.get("errcode")))){
            return  "成员票据无效";
        }
        // 构造请求体数据
        JSONObject requestBody = new JSONObject();
        requestBody.put("user_ticket", String.valueOf(result.get("user_ticket")));
        // 发送 POST 请求
        String userInfoUrl = "https://qyapi.weixin.qq.com/cgi-bin/auth/getuserdetail?access_token="+accessToken;
        HttpResponse response = HttpRequest.post(userInfoUrl)
                .body(requestBody.toString())
                .execute();
         log.info("从企微接口:\n获取访问用户身份信息结果:{}",response);
        return response.body();
    }

    /**
     * 推送授权链接
     *
     * @param userId      用户id
     * @param serviceName 服务名称
     * @param url         url
     * @return {@link String}
     */
    public String sendTextCardMsg(String userId, String serviceName, String url) {
        String s = "";
        try {
            //微信消息对象
            WxCpMessageServiceImpl wxCpMessageService = new WxCpMessageServiceImpl(WxConfig.getWxCpService(redisTemplateString));
            WxCpMessage textcardMsg = new WxCpMessage();
            textcardMsg.setSafe("0");
            //设置消息类型
            textcardMsg.setMsgType("textcard");
            //设置发送用户
            textcardMsg.setToUser(userId);
//            textcardMsg.setToParty("部门id");
//            textcardMsg.setToTag("标签");
            //发送的标题
            textcardMsg.setTitle("授权登入通知");
            //发送内容
            textcardMsg.setDescription(serviceName+"请求通过企业微信授权登入，点击该信息认证授权！");
            //设置跳转；可以自己制作一个网页
            textcardMsg.setUrl(url);
            textcardMsg.setBtnTxt("详情");
            WxCpMessageSendResult result = wxCpMessageService.send(textcardMsg);
            s = result.toString();
            log.info(textcardMsg.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return s;
    }




    @GetMapping("/receiveMessage")
    public ResponseEntity<ByteArrayResource> receiveMessage() {
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wwe24d68910965e032&redirect_uri=https%3A%2F%2F8164c0cc874549a6aa31385aebfea4a8.apig.cn-east-3.huaweicloudapis.com&response_type=code&scope=snsapi_base&state=TEST6666#wechat_redirect";
        QrConfig qrConfig = new QrConfig();
        qrConfig.setHeight(300);
        qrConfig.setWidth(300);
        ByteArrayOutputStream qrCodeStream = new ByteArrayOutputStream();
        QrCodeUtil.generate(url, qrConfig, "png", qrCodeStream);
        ByteArrayResource resource = new ByteArrayResource(qrCodeStream.toByteArray());
        IoUtil.close(qrCodeStream);

        return ResponseEntity.status(HttpStatus.OK)
                .header("Content-Type", "image/png")
                .header("Content-Disposition", "attachment; filename=qrcode.png")
                .body(resource);

    }

}
